package com.example.hostsys.service;

import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.auth.COSCredentials;
import com.qcloud.cos.http.HttpMethodName;
import com.qcloud.cos.region.Region;
import com.tencent.cloud.CosStsClient;
import org.json.JSONObject;
import org.springframework.stereotype.Service;

import java.net.URL;
import java.util.Date;
import java.util.Map;
import java.util.TreeMap;


@Service
public class UploadService {
    //请自行填写
    String secretId = "";
    String secretKey = "";
    String bucketName = "";
    String region = "";


    public Map<String,Object> getCred(String name){
        TreeMap<String, Object> config = new TreeMap<String, Object>();

        config.put("SecretId", secretId);
        config.put("SecretKey", secretKey);

        // 临时密钥有效时长，单位是秒，默认1800秒，目前主账号最长2小时（即7200秒），子账号最长36小时（即129600秒）
        config.put("durationSeconds", 3600);

        config.put("bucket", bucketName);
        config.put("region", region);

        // 这里改成允许的路径前缀，可以根据自己网站的用户登录态判断允许上传的具体路径，例子：a.jpg 或者 a/* 或者 * 。
        // 如果填写了“*”，将允许用户访问所有资源；除非业务需要，否则请按照最小权限原则授予用户相应的访问权限范围。
        config.put("allowPrefix", "house/"+name+"/*");

        // 密钥的权限列表。简单上传、表单上传和分片上传需要以下的权限，其他权限列表请看 https://cloud.tencent.com/document/product/436/31923
        String[] allowActions = new String[] {
                // 简单上传
                "name/cos:PutObject",
                // 表单上传、小程序上传
                "name/cos:PostObject",
                // 分片上传
                "name/cos:InitiateMultipartUpload",
                "name/cos:ListMultipartUploads",
                "name/cos:ListParts",
                "name/cos:UploadPart",
                "name/cos:CompleteMultipartUpload"
        };
        config.put("allowActions", allowActions);
        try {
            JSONObject credential = CosStsClient.getCredential(config);
            return credential.toMap();
        } catch (Exception e) {
            throw new IllegalArgumentException("no valid secret !");
        }
    }

    public String getTK(String mime, String house,String name) {

        COSCredentials cred = new BasicCOSCredentials(secretId, secretKey);
        ClientConfig clientConfig = new ClientConfig(new Region(region));
        COSClient cosClient = new COSClient(cred, clientConfig);
        Date expirationTime = new Date(System.currentTimeMillis() + 3600L * 1000L);
        String key = "User_"+ name +"_";
        URL url = cosClient.generatePresignedUrl(bucketName, key, expirationTime, HttpMethodName.PUT);
        return (url.toString());
    }
}
